import { useEffect, useRef, useState } from "react"

export interface useInfiniteScrollOptions {
  initPage?: number //初始加载的页面，默认是1
  initPageSize?: number //每页加载数量，默认是10条
  refresh?: any[] //刷新依赖
}
export type useInfiniteScrollRequest = (
  pageNo: number,
  pageSize: number,
) => Promise<{ data?: any[]; total?: number }>

export type useInfiniteScrollReturn = [
  list: any[],
  hasMore: boolean,
  loadMore: (isRetry: boolean) => Promise<void>,
]
/**
 * 无限滚动hook
 * @param request 一个异步函数，接收两个参数：pageNo,pageSize;函数内同步请求数据接口，返回值须包含total和data, eg: { data:[],total:100 }
 * @param options
 * @returns [ list, hasMore, loadMore ] list为加载的列表数组
 */
const useInfiniteScroll = (
  request: useInfiniteScrollRequest,
  options?: useInfiniteScrollOptions,
): useInfiniteScrollReturn => {
  const { initPage = 1, initPageSize = 10, refresh = [] } = options || {}
  const [hasMore, setHasMore] = useState(true)
  const [list, setList] = useState([])
  const pager = useRef<{ pageNo: number; pageSize: number }>({
    pageNo: initPage,
    pageSize: initPageSize,
  })
  const loadMore = async () => {
    const { data = [], total = 0 } = await request(
      pager.current.pageNo,
      pager.current.pageSize,
    )
    pager.current.pageNo = pager.current.pageNo + 1
    setHasMore(total > list.length + data?.length)
    setList((prev: any) => prev.concat(data))
  }
  useEffect(() => {
    setList([])
    pager.current.pageNo = 1
    //loadMore()
  }, refresh)
  return [list, hasMore, loadMore]
}

export default useInfiniteScroll
